package com.xinyue.server.common.server;

import java.util.List;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.CacheRefreshedEvent;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.xinyue.logger.GameLogUtil;

@Service
public class ServerInstanceManager {
    private Logger logger = LoggerFactory.getLogger(ServerInstanceManager.class);
    @Autowired
    private EurekaClient eurekaClient;

    @PostConstruct
    public void init() {
        this.refreshRegisterServerInstance();
        eurekaClient.registerEventListener((e) -> {
            GameLogUtil.ScheduleLogger.info("eureka event :{}", e.getClass().getName());
            if (e instanceof CacheRefreshedEvent) {
                this.refreshRegisterServerInstance();
            }
        });
    }

    private void refreshRegisterServerInstance() {
        GameLogUtil.ScheduleLogger.debug("====开始拉取集群中的服务====");
        List<Application> applications = eurekaClient.getApplications().getRegisteredApplications();
        for (Application application : applications) {
            List<InstanceInfo> instanceInfos = application.getInstancesAsIsFromEureka();
            for (InstanceInfo instanceInfo : instanceInfos) {
                GameLogUtil.ScheduleLogger.debug(instanceInfo.toString());
            }
            GameLogUtil.ScheduleLogger.debug("-----------");
        }
        GameLogUtil.ScheduleLogger.debug("====接取到集群中[{}]个服务====", applications.size());
    }
}
